<?php
/* ******************************
 * WSDL aJax actions
 * ******************************
 */

set_time_limit(0);

include('../../includes/classes/core.php');
include('../../includes/classes/wsdl.class.php');
 

$action		= $_REQUEST['act'];
$error		= '';
$data		= '';
$properties = GetCompanyProperties();

$host 		= 'eservices.rs.ge';
$port 		= 443;
$timeout 	= 2;

$wsdl	= new wsdl('http://services.rs.ge/WayBillService/WayBillService.asmx?WSDL', $properties['su'], $properties['sp']);

if($fp = fsockopen($host, $port, $timeout)){

	switch ($action) {
		case 'sync':
			$array = array("create_date_s"		=>	$_REQUEST['create_date_s'],
						   "create_date_e"		=>	$_REQUEST['create_date_e'],
						   "waybill_number"		=>	$_REQUEST['waybill_number'],
						   "seller_tin"			=>  $_REQUEST['seller_tin']);

			$array = array_diff($array, array(''));

			if(empty($array)){
				$error = 'შეავსეთ სინქრონიზაციისათვის აუცილებელი ველი(ები)!';
			}else{
				$params = arrayToObject($array);

				$arr = $wsdl->get_buyer_waybills($params);

				for ($i = 0; $i < count($arr); $i++) {
					$wsdl->set_waybill_id($arr[$i]);
					$wsdl->get_waybill(1);
				}

				$arr = $wsdl->get_waybills($params);

				for ($i = 0; $i < count($arr); $i++) {
					$wsdl->set_waybill_id($arr[$i]);
					$wsdl->get_waybill(0);
				}
			}

			break;
		case 'send_overhead':
			$overhead_id	= $_REQUEST['id'];
			$row			= GetOverhead($overhead_id);
			$result			= GetOverheadDetails($overhead_id);
			$root			= new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><WAYBILL/>");

			$first = $root->addChild('SUB_WAYBILLS');
			$first = $root->addChild('GOODS_LIST');

			while ($row_det = mysql_fetch_assoc($result)) {
				//Start Goods
				$second = $first->addChild('GOODS');
				$second->addChild('ID', 			0);
				$second->addChild('W_NAME', 		$row_det['name']);
				$second->addChild('UNIT_ID', 		$row_det['unit_id']);
				$second->addChild('QUANTITY', 		$row_det['quantity']);
				$second->addChild('PRICE', 			$row_det['price']);
				$second->addChild('AMOUNT', 		$row_det['amount']);
				$second->addChild('BAR_CODE', 		$row_det['bar_code']);
				$second->addChild('A_ID', 			$row_det['a_id']);
				$second->addChild('VAT_TYPE', 		$row_det['vat_type']);
				$second->addChild('STATUS', 		$row_det['status']);
				$second->addChild('QUANTITY_F', 	$row_det['quantity_f']);
				//End Goods
			}

			$root->addChild('ID',  					0);
			$root->addChild('TYPE',  				$row['type']);
			$root->addChild('CREATE_DATE',  		c_data($row['create_date']));
			$root->addChild('BUYER_TIN',  			$row['buyer_tin']);
			$root->addChild('CHEK_BUYER_TIN',  		$row['check_buyer_tin']);
			$root->addChild('BUYER_NAME',  			$row['buyer_name']);
			$root->addChild('START_ADDRESS',  		$row['start_address']);
			$root->addChild('END_ADDRESS',  		$row['end_address']);
			$root->addChild('DRIVER_TIN',  			$row['driver_tin']);
			$root->addChild('CHEK_DRIVER_TIN',  	$row['check_driver_tin']);
			$root->addChild('DRIVER_NAME',  		$row['driver_name']);
			$root->addChild('TRANSPORT_COAST',  	$row['transport_coast']);
			$root->addChild('RECEPTION_INFO',  		$row['reception_info']);
			$root->addChild('RECEIVER_INFO',  		$row['receiver_info']);
			$root->addChild('DELIVERY_DATE',  		c_data($row['delivery_date']));
			$root->addChild('STATUS',  				$row['status']);
			$root->addChild('SELER_UN_ID',  		$row['seller_un_id']);
			$root->addChild('ACTIVATE_DATE',  		c_data($row['activate_date']));
			$root->addChild('PAR_ID',  				$row['par_id']);
			$root->addChild('FULL_AMOUNT',  		$row['full_amount']);
			$root->addChild('FULL_AMOUNT_TXT',  	$row['full_amount_txt']);
			$root->addChild('CAR_NUMBER',  			GetCarNumber($row['car_number']));
			$root->addChild('WAYBILL_NUMBER',  		$row['waybill_number']);
			$root->addChild('CLOSE_DATE',  			c_data($row['close_date']));
			$root->addChild('S_USER_ID',  			$row['s_user_id']);
			$root->addChild('BEGIN_DATE',  			c_data($row['begin_date']));
			$root->addChild('TRAN_COST_PAYER',  	$row['tran_cost_payer']);
			$root->addChild('TRANS_ID',  			$row['trans_id']);
			$root->addChild('TRANS_TXT',  			$row['trans_txt']);
			$root->addChild('COMMENT',  			$row['comment']);
			$root->addChild('IS_CONFIRMED',  		$row['is_confirmed']);
			$root->addChild('CONFIRMATION_DATE',  	c_data($row['confirmation_date']));
			$root->addChild('SELLER_TIN',  			$row['seller_tin']);
			$root->addChild('SELLER_NAME',  		$row['seller_name']);
			$root->addChild('CATEGORY',  			$row['category']);
			$root->addChild('ORIGIN_TYPE',  		$row['origin_type']);
			$root->addChild('ORIGIN_TEXT',  		$row['origin_text']);

			$doc		= dom_import_simplexml($root);
			$xml		= $doc->ownerDocument->saveXML($doc->ownerDocument->documentElement);

			$wsdl_res	= $wsdl->save_waybill($xml);

			if($wsdl_res['status'] == 0){
				SetOverhead($overhead_id, $wsdl_res['rs_id'], $wsdl_res['waybill_number']);
			}else{
				$error = $wsdl->get_error($wsdl_res[status]);
			}

			break;
		case 'send_aletter':
			$aletter_id		= $_REQUEST['id'];
			$row			= GetALetter($aletter_id);
			$result			= GetALetterDetails($aletter_id);
			$root			= new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><WAYBILL/>");
			$first = $root->addChild('SUB_WAYBILLS');
			$first = $root->addChild('GOODS_LIST');

			while ($row_det = mysql_fetch_assoc($result)) {
				//Start Goods
				$second = $first->addChild('GOODS');
				$second->addChild('ID', 			$row_det['goods_id']);
				$second->addChild('W_NAME', 		$row_det['name']);
				$second->addChild('UNIT_ID', 		1);
				$second->addChild('QUANTITY', 		$row_det['quantity']);
				$second->addChild('PRICE', 			0);
				$second->addChild('AMOUNT', 		0);
				$second->addChild('BAR_CODE', 		$row_det['id']);
				$second->addChild('A_ID', 			'');
				$second->addChild('STATUS', 		1);
				$second->addChild('QUANTITY_F', 	$row_det['quantity']);
				//End Goods
			}
			
		if ( $row['TRANSPORTER_TIN'] !=0 & $_REQUEST[trans_type]>0) {
		      $root->addChild('TRANS_ID'       ,    7);
		      $root->addChild('STATUS',  			8);
		      $root->addChild('TRANSPORTER_TIN',	$row['TRANSPORTER_TIN']) ; 
		      $root->addChild('CHEK_BUYER_TIN',  	1);
		      $root->addChild('CHEK_DRIVER_TIN',  	1);
		}else{
		    $root->addChild('TRANS_ID',  			1);	
		    $root->addChild('CAR_NUMBER',  			$row['car']);
		    $root->addChild('DRIVER_NAME',  		$row['driver_name']);
		    $root->addChild('DRIVER_TIN',  			$row['driver_tin']);
		    $root->addChild('CHEK_DRIVER_TIN',  	0);		
			$root->addChild('CHEK_BUYER_TIN',  		0);
			$root->addChild('BUYER_NAME',  			'');	
			$root->addChild('RECEPTION_INFO',  		'');
			$root->addChild('RECEIVER_INFO',  		'');
			$root->addChild('DELIVERY_DATE',  		'');	
			$root->addChild('STATUS',  				1);
			$root->addChild('ACTIVATE_DATE',  		'');
			$root->addChild('PAR_ID',  				'');
			$root->addChild('FULL_AMOUNT',  		0);
			$root->addChild('FULL_AMOUNT_TXT',  	'');
			$root->addChild('WAYBILL_NUMBER',  		0);
			$root->addChild('CLOSE_DATE',  			'');
			$root->addChild('S_USER_ID',  			0);
			$root->addChild('BEGIN_DATE',  			'');
			$root->addChild('TRAN_COST_PAYER',  	1);			
			$root->addChild('TRANS_TXT',  			'');
			$root->addChild('COMMENT',  			'ხელშეკრულების თანახმად კარტრიჯების წამოღება '. $row['client'] .' -დან');
			$root->addChild('IS_CONFIRMED',  		0);
			$root->addChild('CONFIRMATION_DATE',  	'');
			$root->addChild('CATEGORY',  			0);
			$root->addChild('ORIGIN_TYPE',  		0);
			$root->addChild('ORIGIN_TEXT',  		'');
			$root->addChild('BUYER_S_USER_ID',  	0);
		}
		
		    $root->addChild('TRANSPORT_COAST',		$_REQUEST['price']) ; //.
		    $root->addChild('ID',  					$row['overhead_id']);
		    $root->addChild('CREATE_DATE',  		'');
		    $root->addChild('BUYER_TIN',  			$row['buyer_tin']);		    
    		$root->addChild('START_ADDRESS',  		$row['startAddress']);
    		$root->addChild('END_ADDRESS',  		$row['endAddress']);
		    $root->addChild('TYPE',  				1);
		    $root->addChild('SELER_UN_ID',  		$row['un_id']);
		    $root->addChild('SELLER_TIN',  			$row['seller_tin']);
		    $root->addChild('SELLER_NAME',  		$row['seller_name']);

			$doc		= dom_import_simplexml($root);
			$xml		= $doc->ownerDocument->saveXML($doc->ownerDocument->documentElement);


			$wsdl_res	= $wsdl->save_waybill($xml);

			if($wsdl_res['status'] == 0){
				SetALetterOverhead($aletter_id, $wsdl_res['rs_id'],$_REQUEST['price']);
				SetALetterDetailsOverhead($aletter_id, $wsdl_res['goods_list']);
			}else{
				$error = $wsdl->get_error($wsdl_res[status]);
			}

			break;

		case 'send_bletter':
			$aletter_id		= $_REQUEST['id'];
			$row			= GetBLetter($aletter_id);
			$result			= GetBLetterDetails($aletter_id);
			$root			= new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><WAYBILL/>");

			$first = $root->addChild('SUB_WAYBILLS');
			$first = $root->addChild('GOODS_LIST');

			while ($row_det = mysql_fetch_assoc($result)) {
				//Start Goods
				$second = $first->addChild('GOODS');
				$second->addChild('ID', 			'');
				$second->addChild('W_NAME', 		$row_det['name']);
				$second->addChild('UNIT_ID', 		1);
				$second->addChild('QUANTITY', 		$row_det['quantity']);
				$second->addChild('PRICE', 			0);
				$second->addChild('AMOUNT', 		0);
				$second->addChild('BAR_CODE', 		$row_det['id']);
				$second->addChild('A_ID', 			'');
				$second->addChild('STATUS', 		1);
				$second->addChild('QUANTITY_F', 	$row_det['quantity']);
				//End Goods
			}
			
			if ( $row['TRANSPORTER_TIN'] !=0 & $_REQUEST[trans_type]>0) {
			    $root->addChild('TRANS_ID'       ,  7);
			    $root->addChild('STATUS',  			8);
			    $root->addChild('TRANSPORTER_TIN',	$row['TRANSPORTER_TIN']) ;
			    $root->addChild('CHEK_DRIVER_TIN',  1);
			    $root->addChild('CHEK_BUYER_TIN',  	1);
			}else{    			
    			$root->addChild('BUYER_NAME',  			'');
    			$root->addChild('DRIVER_TIN',  			$row['driver_tin']);
    			$root->addChild('CHEK_DRIVER_TIN',  	0);
    			$root->addChild('CHEK_BUYER_TIN',  		0);
    			$root->addChild('DRIVER_NAME',  		$row['driver_name']);			
    			$root->addChild('RECEPTION_INFO',  		'');
    			$root->addChild('RECEIVER_INFO',  		'');
    			$root->addChild('DELIVERY_DATE',  		'');
    			$root->addChild('STATUS',  				1);			
    			$root->addChild('ACTIVATE_DATE',  		'');
    			$root->addChild('PAR_ID',  				'');
    			$root->addChild('FULL_AMOUNT',  		0);
    			$root->addChild('FULL_AMOUNT_TXT',  	'');
    			$root->addChild('CAR_NUMBER',  			$row['car']);
    			$root->addChild('WAYBILL_NUMBER',  		0);
    			$root->addChild('CLOSE_DATE',  			'');
    			$root->addChild('S_USER_ID',  			0);
    			$root->addChild('BEGIN_DATE',  			'');
    			$root->addChild('TRAN_COST_PAYER',  	1);
    			$root->addChild('TRANS_ID',  			1);
    			$root->addChild('TRANS_TXT',  			'');
    			$root->addChild('COMMENT',  			'ხელშეკრულების თანახმად კარტრიჯების დაბრუნება '. $row['client'] .' -ში');
    			$root->addChild('IS_CONFIRMED',  		0);
    			$root->addChild('CONFIRMATION_DATE',  	'');
    			$root->addChild('CATEGORY',  			0);
    			$root->addChild('ORIGIN_TYPE',  		0);
    			$root->addChild('ORIGIN_TEXT',  		'');
    			$root->addChild('BUYER_S_USER_ID',  	0);
			}
			
		    $root->addChild('TRANSPORT_COAST',		$_REQUEST['price']) ; //.
		    $root->addChild('ID',  					$row['overhead_id']);
		    $root->addChild('CREATE_DATE',  		'');
		    $root->addChild('BUYER_TIN',  			$row['buyer_tin']);  
    		$root->addChild('START_ADDRESS',  		$row['startAddress']);
    		$root->addChild('END_ADDRESS',  		$row['endAddress']);
		    $root->addChild('TYPE',  				1);
		    $root->addChild('SELER_UN_ID',  		$row['un_id']);
		    $root->addChild('SELLER_TIN',  			$row['seller_tin']);
		    $root->addChild('SELLER_NAME',  		$row['seller_name']);
		    
			$doc		= dom_import_simplexml($root);
			$xml		= $doc->ownerDocument->saveXML($doc->ownerDocument->documentElement);

			

			$wsdl_res	= $wsdl->save_waybill($xml);



			if($wsdl_res['status'] == 0){
				SetBLetterOverhead($aletter_id, $wsdl_res['rs_id']);
			}else{
				$error = $wsdl->get_error($wsdl_res[status]);
			}

			break;

		case 'send_dletter':
	    
			$dletter_id		= $_REQUEST['id'];
			$row			= GetDLetter($dletter_id);
			$result			= GetDLetterDetails($dletter_id);
			$root			= new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><WAYBILL/>");

			$first = $root->addChild('SUB_WAYBILLS');
			$first = $root->addChild('GOODS_LIST');

			while ($row_det = mysql_fetch_assoc($result)) {
				//Start Goods
				$second = $first->addChild('GOODS');
				$second->addChild('ID', 			$row_det['goods_id']);
				$second->addChild('W_NAME', 		$row_det['name']);
				$second->addChild('UNIT_ID', 		1);
				$second->addChild('QUANTITY', 		$row_det['quantity']);
				$second->addChild('PRICE', 			0);
				$second->addChild('AMOUNT', 		0);
				$second->addChild('BAR_CODE', 		$row_det['id']);
				$second->addChild('A_ID', 			'');
				$second->addChild('STATUS', 		1);
				$second->addChild('QUANTITY_F', 	$row_det['quantity']);
				//End Goods
			}		    	
		    if ( $row['TRANSPORTER_TIN'] !=0 & $_REQUEST[trans_type]>0) {		        
		        $root->addChild('TRANS_ID',             7);
		        $root->addChild('STATUS',  			    8);
		        $root->addChild('TRANSPORTER_TIN',	$row['TRANSPORTER_TIN']) ;
		        $root->addChild('CHEK_BUYER_TIN',  		1);
		        $root->addChild('CHEK_DRIVER_TIN',  	1);
		    }else{
		        $root->addChild('TRANS_ID',  			1);
		        $root->addChild('CAR_NUMBER',  			$row['car']);
		        $root->addChild('DRIVER_NAME',  		$row['driver_name']);
		        $root->addChild('DRIVER_TIN',  			$row['driver_tin']);
		        $root->addChild('CHEK_DRIVER_TIN',  	0);
		        $root->addChild('CHEK_BUYER_TIN',  		0);
		        $root->addChild('BUYER_NAME',  			'');
		        $root->addChild('RECEPTION_INFO',  		'');
		        $root->addChild('RECEIVER_INFO',  		'');
		        $root->addChild('DELIVERY_DATE',  		'');
		        $root->addChild('STATUS',  				1);
		        $root->addChild('ACTIVATE_DATE',  		'');
		        $root->addChild('PAR_ID',  				'');
		        $root->addChild('FULL_AMOUNT',  		0);
		        $root->addChild('FULL_AMOUNT_TXT',  	'');
		        $root->addChild('WAYBILL_NUMBER',  		0);
		        $root->addChild('CLOSE_DATE',  			'');
		        $root->addChild('S_USER_ID',  			0);
		        $root->addChild('BEGIN_DATE',  			'');
		        $root->addChild('TRAN_COST_PAYER',  	1);
		        $root->addChild('TRANS_TXT',  			'');
		        $root->addChild('COMMENT',  			'ხელშეკრულების თანახმად კარტრიჯების წამოღება '. $row['client'] .' -დან');
		        $root->addChild('IS_CONFIRMED',  		0);
		        $root->addChild('CONFIRMATION_DATE',  	'');
		        $root->addChild('CATEGORY',  			0);
		        $root->addChild('ORIGIN_TYPE',  		0);
		        $root->addChild('ORIGIN_TEXT',  		'');
		        $root->addChild('BUYER_S_USER_ID',  	0);
		    }
		    
		    $root->addChild('TRANSPORT_COAST',		$_REQUEST['price']) ; //.
		    $root->addChild('ID',  					$row['overhead_id']);
		    $root->addChild('CREATE_DATE',  		'');
		    $root->addChild('BUYER_TIN',  			$row['buyer_tin']);
		    $root->addChild('START_ADDRESS',  		$row['start_address']);
		    $root->addChild('END_ADDRESS',  		$row['endAddress']);
		    $root->addChild('TYPE',  				1);
		    $root->addChild('SELER_UN_ID',  		$row['un_id']);
		    $root->addChild('SELLER_TIN',  			$row['seller_tin']);
		    $root->addChild('SELLER_NAME',  		$row['seller_name']);
   	    
		    
//////////------------------	

			$doc		= dom_import_simplexml($root);
			$xml		= $doc->ownerDocument->saveXML($doc->ownerDocument->documentElement);


			$wsdl_res	= $wsdl->save_waybill($xml);
			if($wsdl_res['status'] == 0){
				SetDLetterOverhead($dletter_id, $wsdl_res['rs_id']);
				SetDLetterDetailsOverhead($dletter_id, $wsdl_res['goods_list']);
			}else{
				$error = $wsdl->get_error($wsdl_res[status]);
			}

			break;

			case 'send_eletter':
				$dletter_id		= $_REQUEST['id'];
				$row			= GetELetter($dletter_id);
				$result			= GetELetterDetails($dletter_id);
				$root			= new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><WAYBILL/>");

				$first = $root->addChild('SUB_WAYBILLS');
				$first = $root->addChild('GOODS_LIST');

				while ($row_det = mysql_fetch_assoc($result)) {
					//Start Goods
					$second = $first->addChild('GOODS');
					$second->addChild('ID', 			'');
					$second->addChild('W_NAME', 		$row_det['name']);
					$second->addChild('UNIT_ID', 		1);
					$second->addChild('QUANTITY', 		$row_det['quantity']);
					$second->addChild('PRICE', 			0);
					$second->addChild('AMOUNT', 		0);
					$second->addChild('BAR_CODE', 		$row_det['id']);
					$second->addChild('A_ID', 			'');
					$second->addChild('STATUS', 		1);
					$second->addChild('QUANTITY_F', 	$row_det['quantity']);
					//End Goods
				}

			if ( $row['TRANSPORTER_TIN'] !=0 & $_REQUEST[trans_type]>0) {		        
		        $root->addChild('TRANS_ID',             7);
		        $root->addChild('STATUS',  			    8);
		        $root->addChild('TRANSPORTER_TIN',	$row['TRANSPORTER_TIN']) ;
		        $root->addChild('CHEK_BUYER_TIN',  		1);
		        $root->addChild('CHEK_DRIVER_TIN',  	1);
		    }else{
		        $root->addChild('TRANS_ID',  			1);
		        $root->addChild('CAR_NUMBER',  			$row['car']);
		        $root->addChild('DRIVER_NAME',  		$row['driver_name']);
		        $root->addChild('DRIVER_TIN',  			$row['driver_tin']);
		        $root->addChild('CHEK_DRIVER_TIN',  	0);
		        $root->addChild('CHEK_BUYER_TIN',  		0);
		        $root->addChild('BUYER_NAME',  			'');
		        $root->addChild('RECEPTION_INFO',  		'');
		        $root->addChild('RECEIVER_INFO',  		'');
		        $root->addChild('DELIVERY_DATE',  		'');
		        $root->addChild('STATUS',  				1);
		        $root->addChild('ACTIVATE_DATE',  		'');
		        $root->addChild('PAR_ID',  				'');
		        $root->addChild('FULL_AMOUNT',  		0);
		        $root->addChild('FULL_AMOUNT_TXT',  	'');
		        $root->addChild('WAYBILL_NUMBER',  		0);
		        $root->addChild('CLOSE_DATE',  			'');
		        $root->addChild('S_USER_ID',  			0);
		        $root->addChild('BEGIN_DATE',  			'');
		        $root->addChild('TRAN_COST_PAYER',  	1);
		        $root->addChild('TRANS_TXT',  			'');
		        $root->addChild('COMMENT',  			'ხელშეკრულების თანახმად კარტრიჯების წამოღება '. $row['client'] .' -დან');
		        $root->addChild('IS_CONFIRMED',  		0);
		        $root->addChild('CONFIRMATION_DATE',  	'');
		        $root->addChild('CATEGORY',  			0);
		        $root->addChild('ORIGIN_TYPE',  		0);
		        $root->addChild('ORIGIN_TEXT',  		'');
		        $root->addChild('BUYER_S_USER_ID',  	0);
		    }
		    
		    $root->addChild('TRANSPORT_COAST',		$_REQUEST['price']) ; //.
		    $root->addChild('ID',  					$row['overhead_id']);
		    $root->addChild('CREATE_DATE',  		'');
		    $root->addChild('BUYER_TIN',  			$row['buyer_tin']);
		    $root->addChild('START_ADDRESS',  		$row['start_address']);
		    $root->addChild('END_ADDRESS',  		$row['endAddress']);
		    $root->addChild('TYPE',  				1);
		    $root->addChild('SELER_UN_ID',  		$row['un_id']);
		    $root->addChild('SELLER_TIN',  			$row['seller_tin']);
		    $root->addChild('SELLER_NAME',  		$row['seller_name']);

				$doc		= dom_import_simplexml($root);
				$xml		= $doc->ownerDocument->saveXML($doc->ownerDocument->documentElement);


				$wsdl_res	= $wsdl->save_waybill($xml);
				if($wsdl_res['status'] == 0){
					SetELetterOverhead($dletter_id, $wsdl_res['rs_id']);
				}else{
					$error = $wsdl->get_error($wsdl_res[status]);
				}

				break;

		case 'finish_overhead':
			$rs_id = $_REQUEST['rs_id'];

			$wsdl->set_waybill_id($rs_id);
			$wsdl_res	= $wsdl->close_waybill();
		//	print_r($wsdl_res)	;
			if( !empty($wsdl_res[date][end]) )
			{
			    $error = 'ვიღაცამ რ-ს ზე უკვე დაასრულა';
			    FinishOverhead($rs_id, $wsdl_res[date]);
			}else
			if($wsdl_res[message] != 1){
				$error = $wsdl_res[message];
			}else{
			     $error = 'წარმატებით დასრულდა';
				FinishOverhead($rs_id);
			}

			break;
		case  'RefOverheadRS':
			$rs_id	= $_REQUEST['rs_id'];
			$wsdl->set_waybill_id($rs_id);
			$wsdl_res	= $wsdl->ref_waybill();


			if($wsdl_res != "წარმატებით გაუქმდა"){
				$error = $wsdl_res;
			}else{
				$error = RefOverhead($rs_id);
				$error = $wsdl_res;
			}

			break;
		case 'confirm_overhead':
			$overhead_id	= $_REQUEST['id'];
			$rs_id			= $_REQUEST['rs_id'];

			$wsdl->set_waybill_id($rs_id);
			$wsdl_res	= $wsdl->confirm_waybill();

			if($wsdl_res){
				ConfirmOverhead($overhead_id);
			}else{
				$error = 'ვერ მოხერხდა ზედნადების დადასტურება!';
			}

			break;
		case 'reject_overhead':
			$overhead_id	= $_REQUEST['id'];

			RejectOverhead($overhead_id);

			break;
		case 'create_service_user':
			$user_name 		= $_REQUEST['user_name'];
			$user_password 	= $_REQUEST['user_password'];

			$ip 			= $wsdl->what_is_my_ip();
			$su_name 		= $_REQUEST['su_name'];

			$su 			= $_REQUEST['su'];
			$sp 			= $_REQUEST['sp'];

			$wsdl_res	= $wsdl->create_service_user($user_name, $user_password, $ip, $su_name, $su, $sp);

			if ($wsdl_res){
				mysql_query("
								UPDATE 		`company_properties`
							 	SET			`name`      = '$user_name',
											`password`	= '$user_password',
	                    					`ip`        = '$ip',
	                    					`su_name`  	= '$su_name',
	                    					`su`        = '$su',
	                     					`sp`        = '$sp'
								WHERE 		`id`		= 1
							");
			}else{
				$error = 'ვერ მოხერხდა მომხმარებლის შექმნა!';
			}

			break;
		case 'chek_service_user':
			$s_user 	= $wsdl->chek_service_user();
			mysql_query("
							UPDATE 		`company_properties`
						 	SET			`s_user_id` = $s_user[s_user_id],
						 				`un_id` 	= $s_user[un_id]
							WHERE 		`id`		= 1
						");

			break;
		default:
	       $error = 'Action is Null';
	}

} else {
	$error = 'კავშირის შეფერხება RS.ge -ზე, გთხოვთ სცადეთ მოგვიანებით!!!';
}
fclose($fp);

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	WSDL Functions
 * ******************************
 */

function arrayToObject($d) {
	if (is_array($d)) {
		/*
		 * Return array converted to object
		* Using __FUNCTION__ (Magic constant)
		* for recursive call
		*/
		return (object) array_map(__FUNCTION__, $d);
	}
	else {
		// Return object
		return $d;
	}
}

function GetCompanyProperties()
{
	$res = mysql_fetch_assoc(mysql_query("SELECT 	`su`,
    											 	`sp`
									      FROM 		`company_properties`"));
	return $res;
}

function GetALetter($aletter_id){
	global $error;
	$result = mysql_query("  SELECT			`client`.`name` 				AS client,
											`company_properties`.`tin` 		AS `buyer_tin`,
											`company_properties`.`address` 	AS `endAddress`,
											CONCAT('ქ. ', `cities`.`name`, ', ', `client_objects`.address_name , ' ', `address_types`.`name` , ' ', `client_objects`.`address_number` )	AS `startAddress`,
											`persons`.`name` 				AS `driver_name`,
											`persons`.`tin` 				AS `driver_tin`,
											`company_properties`.`un_id`	AS `un_id`,
											`object`.`name` 				AS `car`,
											`company_properties`.`tin` 		AS `seller_tin`,
											`company_properties`.`name` 	AS `seller_name`,
	                                        `transporter_company`.tin AS TRANSPORTER_TIN,     
	                                        `a_letter`.a_trans_price AS trans_price,  
											`a_letter`.`overhead_id`		AS `overhead_id`
							FROM 			`company_properties`, `a_letter`
							LEFT JOIN    	`client_objects` ON `a_letter`.`client_object_id` = `client_objects`.`id`
							LEFT JOIN 		`client` ON `client`.`id` = `client_objects`.`client_id`
							LEFT JOIN     	`persons` ON `persons`.`id` = `a_letter`.`receiver`
							LEFT JOIN   	`object` ON `object`.`id` = `a_letter`.`car_id`
	    					LEFT JOIN       `transporter_company` ON transporter_company.id=client_objects.transporter_company_id
							LEFT JOIN		`address_types` ON `address_types`.`id` = `client_objects`.`address_type`
							LEFT JOIN		`cities` ON `cities`.`id` = client_objects.`region`
							WHERE			`a_letter`.`id` = '$aletter_id'");

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}else{
		$row = mysql_fetch_assoc($result);
		return $row;
	}
}

function GetALetterDetails($aletter_id){
	global $error;
	$result = mysql_query("SELECT	warehouse_detail.id,
                        			`warehouse_detail`.`goods_id`,
                    				`production`.`name`,
                    				COUNT(warehouse_detail.id) as quantity
                    	FROM   warehouse_detail
                    	LEFT JOIN production ON production.id = prod_id
                        LEFT JOIN warehouse ON warehouse.id=warehouse_detail.warehouse_id
                        WHERE warehouse.a_letter_id='$aletter_id' AND warehouse_detail.actived=1
                    	GROUP BY prod_id");

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}else{
		return $result;
	}
}

function GetBLetter($aletter_id){
	global $error;
	$result = mysql_query(" SELECT			`client`.`name` 				AS client,
											`company_properties`.`tin` 		AS `buyer_tin`,
											`company_properties`.`address` 	AS `startAddress`,
											CONCAT('ქ. ', `cities`.`name`, ', ', `client_objects`.address_name , ' ', `address_types`.`name` , ' ', `client_objects`.`address_number` )	AS `endAddress`,
											`persons`.`name` 				AS `driver_name`,
											`persons`.`tin` 				AS `driver_tin`,
	                                        `transporter_company`.tin AS TRANSPORTER_TIN, 
											`company_properties`.`un_id`	AS `un_id`,
											`object`.`name` 				AS `car`,
											`company_properties`.`tin` 		AS `seller_tin`,
											`company_properties`.`name` 	AS `seller_name`,
											`a_letter`.`b_letter_overhead_id`		AS `overhead_id`
							FROM 			`company_properties`, `a_letter`
							LEFT JOIN    	`client_objects` ON `a_letter`.`client_object_id` = `client_objects`.`id`
							LEFT JOIN 		`client` ON `client`.`id` = `client_objects`.`client_id`
							LEFT JOIN     	`persons` ON `persons`.`id` = `a_letter`.`receiver1`
							LEFT JOIN   	`object` ON `object`.`id` = `a_letter`.`car_id`
							LEFT JOIN		`address_types` ON `address_types`.`id` = `client_objects`.`address_type`
	                        LEFT JOIN       `transporter_company` ON transporter_company.id=client_objects.transporter_company_id
	    					LEFT JOIN		`cities` ON `cities`.`id` = client_objects.`region`
							WHERE			`a_letter`.`id` = '$aletter_id'");

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}else{
		$row = mysql_fetch_assoc($result);
		return $row;
	}
}

function GetBLetterDetails($aletter_id){
	global $error;
	$result = mysql_query("SELECT	warehouse_detail.id,
                        			`warehouse_detail`.`goods_id`,
                    				`production`.`name`,
                    				COUNT(warehouse_detail.id) as quantity
                    	FROM   warehouse_detail
                    	LEFT JOIN production ON production.id = prod_id
                        LEFT JOIN warehouse ON warehouse.id=warehouse_detail.warehouse_id
                        WHERE warehouse.a_letter_id='$aletter_id' AND warehouse_detail.actived=1
                    	GROUP BY prod_id");

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}else{
		return $result;
	}
}

function GetDLetter($dletter_id){
	global $error;
	$result = mysql_query(" SELECT			`client`.`name` 				AS client,
											`company_properties`.`tin` 		AS `buyer_tin`,
											`company_properties`.`address` 	AS `endAddress`,
											CONCAT('ქ. ', `cities`.`name`, ', ', `client_objects`.address_name , ' ', `address_types`.`name` , ' ', `client_objects`.`address_number` )	AS start_address,
											`persons`.`name` 				AS `driver_name`,
											`persons`.`tin` 				AS `driver_tin`,
											`company_properties`.`un_id`	AS `un_id`,
	                                        `transporter_company`.tin       AS TRANSPORTER_TIN,   
											`object`.`name` 				AS `car`,
											`company_properties`.`tin` 		AS `seller_tin`,
											`company_properties`.`name` 	AS `seller_name`,
	                                        `d_letter`.d_trans_price AS trans_price,  
											`d_letter`.`overhead_id`		AS `overhead_id`
							FROM 			`company_properties`, `d_letter`
							LEFT JOIN    	`client_objects` ON `d_letter`.`client_object_id` = `client_objects`.`id`
							LEFT JOIN 		`client` ON `client`.`id` = `client_objects`.`client_id`
							LEFT JOIN     	`persons` ON `persons`.`id` = `d_letter`.`receiver`
							LEFT JOIN   	`object` ON `object`.`id` = `d_letter`.`car_id`
							LEFT JOIN		`address_types` ON `address_types`.`id` = `client_objects`.`address_type`
							LEFT JOIN       `transporter_company` ON transporter_company.id=client_objects.transporter_company_id
	                        LEFT JOIN		`cities` ON `cities`.`id` = client_objects.`region`
							WHERE			`d_letter`.`id` = '$dletter_id'");//

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}else{
		$row = mysql_fetch_assoc($result);
		return $row;
	}
}

function GetDLetterDetails($dletter_id){
	global $error;
	$result = mysql_query("SELECT	warehouse_detail.id,
                            	    `warehouse_detail`.`goods_id`,
                            	    `production`.`name`,
                            	    COUNT(warehouse_detail.id) as quantity
                    	    FROM   warehouse_detail
                    	    LEFT JOIN production ON production.id = prod_id
                    	    LEFT JOIN warehouse ON warehouse.id=warehouse_detail.warehouse_id
                    	    WHERE warehouse.d_letter_id='$dletter_id' AND warehouse_detail.actived=1
                    	    GROUP BY prod_id");

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}else{
		return $result;
	}
}

function GetELetter($dletter_id){
	global $error;
	$result = mysql_query("  SELECT			`client`.`name` 				AS client,
											`company_properties`.`tin` 		AS `buyer_tin`,
											`company_properties`.`address` 	AS `start_address`,
											CONCAT('ქ. ', `cities`.`name`, ', ', `client_objects`.address_name , ' ', `address_types`.`name` , ' ', `client_objects`.`address_number` )	AS `endAddress`,
											`persons`.`name` 				AS `driver_name`,
											`persons`.`tin` 				AS `driver_tin`,
	                                        `transporter_company`.tin AS TRANSPORTER_TIN, 
											`company_properties`.`un_id`	AS `un_id`,
											`object`.`name` 				AS `car`,
											`company_properties`.`tin` 		AS `seller_tin`,
											`company_properties`.`name` 	AS `seller_name`,
											`d_letter`.`e_letter_overhead_id`		AS `overhead_id`
							FROM 			`company_properties`, `d_letter`
							LEFT JOIN    	`client_objects` ON `d_letter`.`client_object_id` = `client_objects`.`id`
							LEFT JOIN 		`client` ON `client`.`id` = `client_objects`.`client_id`
							LEFT JOIN     	`persons` ON `persons`.`id` = `d_letter`.`receiver1`
							LEFT JOIN   	`object` ON `object`.`id` = `d_letter`.`car_id`
	                        LEFT JOIN       `transporter_company` ON transporter_company.id=client_objects.transporter_company_id
	    					LEFT JOIN		`address_types` ON `address_types`.`id` = `client_objects`.`address_type`
							LEFT JOIN		`cities` ON `cities`.`id` = client_objects.`region`
							WHERE			`d_letter`.`id` = '$dletter_id'");

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}else{
		$row = mysql_fetch_assoc($result);
		return $row;
	}
}

function GetELetterDetails($dletter_id){
	global $error;
	$result = mysql_query("SELECT	warehouse_detail.id,
                        			`warehouse_detail`.`goods_id`,
                    				`production`.`name`,
                    				COUNT(warehouse_detail.id) as quantity
                    	FROM   warehouse_detail
                    	LEFT JOIN production ON production.id = prod_id
                        LEFT JOIN warehouse ON warehouse.id=warehouse_detail.warehouse_id
                        WHERE warehouse.d_letter_id='$dletter_id' AND warehouse_detail.actived=1
                    	GROUP BY prod_id");

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}else{
		return $result;
	}
}

function GetOverhead($overhead_id){
	global $error;
	$result = mysql_query("SELECT *
						   FROM `overhead`
						   WHERE `id` = '$overhead_id'");

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}else{
		$row	= mysql_fetch_assoc($result);
		return $row;
	}
}

function GetOverheadDetails($overhead_id){
	global $error;
	$result = mysql_query("SELECT 	*
						   FROM 	`overhead_detail`
						   WHERE 	`overhead_id` = '$overhead_id' && `quantity` != 0");

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}else{
		return $result;
	}
}

function SetOverhead($overhead_id, $rs_id, $waybill_number){
	global $error;
	$result = mysql_query("UPDATE `overhead`
						   SET 	`rs_id`				= '$rs_id',
								`waybill_number`	= '$waybill_number'
						   WHERE `id` = '$overhead_id'");

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}
}

function ConfirmOverhead($overhead_id){
	global $error;
	$c_date = date('Y-m-d\TH:i:s');
	$result = mysql_query("UPDATE `overhead`
						   SET 	`is_confirmed`				= 2,
								`confirmation_date`			= '$c_date'
						   WHERE `id` = $overhead_id"); //2 is local variable

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
		return null;
	}
}
function RefOverhead($overhead_id){

	global $error;
	$result = mysql_query(" UPDATE	warehouse
                            JOIN    `a_letter` ON warehouse.a_letter_id=a_letter.id
                            JOIN    warehouse_detail ON warehouse_detail.warehouse_id=warehouse.id
                            SET		 a_letter.overhead_id 		= NULL,
                            		 warehouse_detail.goods_id 	= NULL
                            WHERE	a_letter.overhead_id =$overhead_id");//////////////////////-----------a------

	$result.= mysql_query("UPDATE	warehouse
                            JOIN    `d_letter` ON warehouse.d_letter_id=d_letter.id
                            JOIN    warehouse_detail ON warehouse_detail.warehouse_id=warehouse.id
                            SET		 d_letter.overhead_id             = NULL,
                            		 warehouse_detail.goods_id 	      = NULL
                            WHERE	d_letter.overhead_id              =  $overhead_id");//-------------d---------
	$result.= mysql_query(" UPDATE	warehouse
	                       JOIN    `a_letter` ON warehouse.a_letter_id=a_letter.id
	                       JOIN    warehouse_detail ON warehouse_detail.warehouse_id=warehouse.id
	                       SET		 a_letter.b_letter_overhead_id 	   = NULL,
	                                 warehouse_detail.goods_id 	       = NULL
	                       WHERE	a_letter.b_letter_overhead_id      = $overhead_id");

	$result.= mysql_query("UPDATE	warehouse
                    	    JOIN    `d_letter` ON warehouse.d_letter_id=d_letter.id
                    	    JOIN    warehouse_detail ON warehouse_detail.warehouse_id=warehouse.id
                    	    SET		 d_letter.e_letter_overhead_id    = NULL,
                    	             warehouse_detail.goods_id 	      = NULL
                    	    WHERE	 d_letter.e_letter_overhead_id    =  $overhead_id");

	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
	}
	}

function RejectOverhead($overhead_id){
	global $error;
		$result = mysql_query("UPDATE `overhead`
			SET 	`is_confirmed` = -1
			WHERE `id` = '$overhead_id'");
	if(!$result){
		$error	= 'Invalid query: ' . mysql_error();
	}
}

function SetALetterOverhead($letter_id, $overhead_id, $price=0)
{
	mysql_query("	UPDATE	`a_letter`
					SET		`overhead_id` = '$overhead_id',
					        a_trans_price=  '$price'				
					WHERE	`id` = $letter_id");
	mysql_query("   INSERT INTO `rs_wdsl_status`
	                       (`id`,`start_date`)
	               VALUES ('$overhead_id', CURRENT_TIMESTAMP)");

}

function SetALetterDetailsOverhead($letter_id, $goods_list)
{
	for ($i = 0; $i < count($goods_list); $i++) {
		$id			= $goods_list[$i]['id'];
		$bar_code	= $goods_list[$i]['bar_code'];

		mysql_query("	UPDATE	`warehouse_detail`
						SET		`goods_id`	= $id
						WHERE	`id`		= $bar_code");
	}
}

function SetBLetterOverhead($letter_id, $overhead_id)
{
    $price=$_REQUEST['price'];
	mysql_query("	UPDATE	`a_letter`
					SET		`b_letter_overhead_id` = '$overhead_id',
							`status`			   = 5,
					         b_trans_price=  '$price'		
					WHERE	`id` = $letter_id");
	mysql_query("   INSERT INTO `rs_wdsl_status`
                	       (`id`,`start_date`)
                	VALUES ('$overhead_id', CURRENT_TIMESTAMP)");
}


function SetDLetterOverhead($letter_id, $overhead_id)
{
    $price=$_REQUEST['price'];
  	mysql_query("	UPDATE	`d_letter`
					SET		`overhead_id` = '$overhead_id',
					         d_trans_price=  '$price'
					WHERE	`id` = $letter_id");
                	mysql_query("   INSERT INTO `rs_wdsl_status`
                	(`id`,`start_date`)
                	VALUES ('$overhead_id', CURRENT_TIMESTAMP)");
}

function SetDLetterDetailsOverhead($letter_id, $goods_list)
{
	for ($i = 0; $i < count($goods_list); $i++) {
		$id			= $goods_list[$i]['id'];
		$bar_code	= $goods_list[$i]['bar_code'];

		mysql_query("	UPDATE	`warehouse_detail`
						SET		`goods_id`	= $id
						WHERE	`id`		= $bar_code");
	}
}

function SetELetterOverhead($letter_id, $overhead_id)
{
	$price=$_REQUEST['price'];
	mysql_query("	UPDATE	`d_letter`
					SET		`e_letter_overhead_id` = '$overhead_id',
							`status`			   = 5,
					        e_trans_price=  '$price'		
					WHERE	`id` = $letter_id");
	mysql_query("   INSERT INTO `rs_wdsl_status`
	                       (`id`,`start_date`)
	                VALUES ('$overhead_id', CURRENT_TIMESTAMP)");
}

/////////////////
function GetCarNumber($car_id)
{
	if(!empty($car_id)){
		$res = mysql_fetch_assoc(mysql_query("SELECT `name`
											  FROM	 `object`
											  WHERE  `id` = $car_id"));
		return $res['name'];
	}
	return null;
}

function c_data($str){
	if($str != '0000-00-00 00:00:00' && $str != null){
		$b_date = strtotime($str);
		$b_date = date('Y-m-d\TH:i:s', $b_date);
		return $b_date;
	}
	return null;
}

function FinishOverhead($rs_id, $date){

	$c_data = date('Y-m-d H:i:s');

	mysql_query("	UPDATE	`a_letter`
					SET		`finish_date`	= '$c_data',
							`status`		= 6
					WHERE	`b_letter_overhead_id` = '$rs_id'");

	mysql_query("	UPDATE	`d_letter`
					SET		`finish_date`	= '$c_data',
							`status`		= 6
					WHERE	`e_letter_overhead_id` = '$rs_id'");
	mysql_query("	UPDATE	`a_letter`
                	SET		`priority`		= 1
                	WHERE	`overhead_id` = '$rs_id'");
	
	mysql_query("	UPDATE	`d_letter`
                	SET		`priority`		= 1
                	WHERE	`overhead_id` = '$rs_id'");

	mysql_query("   INSERT INTO rs_wdsl_status (id, start_date, end_date)
                    VALUES ($rs_id, '$date[start]', '$date[end]')
                    ON DUPLICATE KEY UPDATE end_date=NOW();");
}

?>